package cn.wb.org.controller;

import cn.wb.base.jwt.UserInfo;
import cn.wb.base.util.AjaxResult;
import cn.wb.base.util.LoginContext;
import cn.wb.base.util.PageList;
import cn.wb.org.domain.Employee;
import cn.wb.org.query.EmployeeQuery;
import cn.wb.org.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController  // @Controller + @ResponseBody
@RequestMapping("/emp")
@Api(value = "员工的API", description = "员工相关的CRUD功能")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;


    /**
     * restful、 风格
     */
    @GetMapping
    public List<Employee> findAll() {
        return employeeService.findAll();
    }


    /**
     * restful 风格 路径变量
     * 如果前端传的参数名称 叫 deptId
     * http://localhost:8080/dept/1
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询")
    public Employee findById(@ApiParam(value = "ID属性", required = true)
                             @PathVariable("id") Long id) {
        return employeeService.findById(id);
    }

    /**
     * 添加/ 修改
     *
     * @return
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Employee employee) {
        if (null == employee.getId()) {
            // 添加
            employeeService.add(employee);
        } else {
            // 编辑
            employeeService.update(employee);
        }
        return AjaxResult.me().success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public AjaxResult deleteById(@PathVariable("id") Long id) {
        employeeService.delete(id);
        return AjaxResult.me().success();
    }

    /**
     * 分页 json格式交互 字符串
     *
     * @RequestBody 接收前端的json数据 转成我们的实体
     */
    @PostMapping
    public PageList<Employee> queryByPage(@RequestBody EmployeeQuery quey, HttpServletRequest request) {
        UserInfo userInfo = LoginContext.getUserInfo();
        if (null != userInfo.getShop()) {
            quey.setShopId(userInfo.getShop().getId());
        }
        return employeeService.queryByPage(quey);
    }

    /**
     * 批量删除
     */
    @PatchMapping
    public AjaxResult batchDetel(@RequestBody List<Long> ids) {
        employeeService.batchDetel(ids);
        return AjaxResult.me().success();
    }

    /**
     * 根据部门id去查询员工集合
     */
    @GetMapping("/findByDeptId/{deptId}")
    public List<Employee> findByDeptId(@PathVariable("deptId") Long deptId) {
        return employeeService.findByDeptId(deptId);
    }

    /**
     * 查询店铺下的员工
     */
    @GetMapping("/list/{shopId}")
    public List<Employee> findListByShopId(@PathVariable("shopId") Long shopId) {
        return employeeService.findListByShopId(shopId);
    }

}
